package cn.com.gridinfo.sooc.core.course.classes.adapter;

import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Interpolator;
import android.view.animation.LinearInterpolator;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;

import com.jeremy.arad.utils.Log;
import com.squareup.picasso.Picasso;

import org.apache.http.message.BasicNameValuePair;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import cn.com.gridinfo.sooc.R;
import cn.com.gridinfo.sooc.core.course.classes.activity.CourseDetailActivity;
import cn.com.gridinfo.sooc.core.course.classes.activity.CourseWebViewActivity;
import cn.com.gridinfo.sooc.core.course.classes.bean.CarourseFigure;
import cn.com.gridinfo.sooc.utils.IntentUtil;
import cn.com.gridinfo.sooc.utils.widget.MySpeedScroller;

public class XnCarouseImageView extends FrameLayout {
    private int count;
//    private ImageLoader mImageLoader;
    private List<ImageView> imageViews;
    private Context context;
    private ViewPager vp;
    private boolean isAutoPlay;
    private int currentItem;
    private int delayTime;
    private LinearLayout ll_dot;
    private List<ImageView> iv_dots;
    private Handler handler = new Handler();
    View xnCarouseView;//轮播图布局
    KannerPagerAdapter kannerPagerAdapter;
    //轮播图列表数据
    private List<CarourseFigure> cfList;

    int mposition;

    public XnCarouseImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        this.context = context;
//        initImageLoader(context);
        initData();
    }

    public XnCarouseImageView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public XnCarouseImageView(Context context) {
        this(context, null);
    }

    private void initData() {
        imageViews = new ArrayList<ImageView>();
        iv_dots = new ArrayList<ImageView>();


        delayTime = 2000;
    }

    public void setImagesUrl(List<CarourseFigure> cfList) {
        this.cfList = cfList;
        imageViews = new ArrayList<ImageView>();
        iv_dots = new ArrayList<ImageView>();
        handler.removeCallbacks(task);



        initLayout();
        initImgFromNet();
        showTime();
//        handler.post(task);
    }

    public void setImagesRes(int[] imagesRes) {
        initLayout();
        initImgFromRes(imagesRes);
        showTime();
    }

    private void initLayout() {
        imageViews.clear();
        if(xnCarouseView == null) {
            xnCarouseView = LayoutInflater.from(context).inflate(
                    R.layout.course_lunbo_slideshow, this, true);

        }
        vp = (ViewPager) xnCarouseView.findViewById(R.id.viewPager);
        vp.removeAllViews();
        ll_dot = (LinearLayout) xnCarouseView.findViewById(R.id.dotLayout);
        ll_dot.removeAllViews();
        iv_dots.clear();

    }

    private void initImgFromRes(int[] imagesRes) {
        count = imagesRes.length;
        for (int i = 0; i < count; i++) {
            ImageView iv_dot = new ImageView(context);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.WRAP_CONTENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT);
            params.leftMargin = 5;
            params.rightMargin = 5;
            iv_dot.setImageResource(R.mipmap.dot_blur);
            ll_dot.addView(iv_dot, params);
            iv_dots.add(iv_dot);
        }
        iv_dots.get(0).setImageResource(R.mipmap.dot_focus);

        for (int i = 0; i <= count + 1; i++) {
            ImageView iv = new ImageView(context);
            iv.setScaleType(ScaleType.FIT_XY);
            if (i == 0) {
                iv.setImageResource(imagesRes[count - 1]);
            } else if (i == count + 1) {
                iv.setImageResource(imagesRes[0]);
            } else {
                iv.setImageResource(imagesRes[i - 1]);
            }
            imageViews.add(iv);
        }
    }

    private void initImgFromNet() {
        count = cfList.size();
        for (int i = 0; i < count; i++) {
            ImageView iv_dot = new ImageView(context);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.WRAP_CONTENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT);
            params.leftMargin = 5;
            params.rightMargin = 5;
            iv_dot.setImageResource(R.mipmap.dot_blur);
            ll_dot.addView(iv_dot, params);
            iv_dots.add(iv_dot);
        }
        iv_dots.get(0).setImageResource(R.mipmap.dot_focus);

        for (int i = 0; i <= count + 1; i++) {
            ImageView iv = new ImageView(context);
            iv.setScaleType(ScaleType.FIT_XY);
            if (i == 0) {
                Picasso.with(context).load(cfList.get(count - 1).getImageurl())
                        .placeholder(R.mipmap.course_placeholder)
                        .error(R.mipmap.course_placeholder)
                        .into(iv);
            } else if (i == count + 1) {
                Picasso.with(context).load(cfList.get(0).getImageurl())
                        .placeholder(R.mipmap.course_placeholder)
                        .error(R.mipmap.course_placeholder)
                        .into(iv);
            } else {
                Picasso.with(context).load(cfList.get(i - 1).getImageurl())
                        .placeholder(R.mipmap.course_placeholder)
                        .error(R.mipmap.course_placeholder)
                        .into(iv);
            }
            imageViews.add(iv);
        }

    }

    private void showTime() {
        if(count>1) {
            isAutoPlay = true;
        }else{
            isAutoPlay = false;

        }
        if(kannerPagerAdapter == null ){
            kannerPagerAdapter = new KannerPagerAdapter();
            vp.setAdapter(kannerPagerAdapter);

            vp.addOnPageChangeListener(new MyOnPageChangeListener());
            try {
                Field mScroller;
                mScroller = ViewPager.class.getDeclaredField("mScroller");
                mScroller.setAccessible(true);
                Interpolator sInterpolator = new LinearInterpolator();
                MySpeedScroller scroller = new MySpeedScroller(

                        vp.getContext(), sInterpolator, 500);
                mScroller.set(vp, scroller);
            }catch (Exception e){

            }

        }else {

//            vp.getAdapter().notifyDataSetChanged();
            kannerPagerAdapter = new KannerPagerAdapter();
            kannerPagerAdapter.notifyDataSetChanged();
            vp.setAdapter(kannerPagerAdapter);
            vp.setFocusable(true);
            vp.setCurrentItem(1);
            currentItem = 1;

        }


        startPlay();
    }

    private void startPlay() {
        if(count>1) {
//            isAutoPlay = true;
            handler.postDelayed(task, 2000);
        }else{
//            handler = null;
//            isAutoPlay = false;

        }

    }


    private final Runnable task = new Runnable() {

        @Override
        public void run() {

            if (isAutoPlay) {
                currentItem = currentItem % (count + 1) + 1;
                Log.d("currentItem:"+currentItem+"-----count:"+count);
                if (currentItem == 1) {
                    vp.setCurrentItem(currentItem, false);
                    handler.post(task);
                } else {
                    vp.setCurrentItem(currentItem);
                    handler.postDelayed(task, 3000);
                }
            } else {
                handler.postDelayed(task, 5000);
            }
        }
    };

    class KannerPagerAdapter extends PagerAdapter {

        @Override
        public int getCount() {
            return imageViews.size();
        }

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == arg1;
        }

        @Override
        public Object instantiateItem(ViewGroup container, final int position) {
            container.addView(imageViews.get(position));
            imageViews.get(position).setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View arg0) {
                    Activity activity = (Activity) context;
                    if(position==0){
                        if("course".equals(cfList.get(0).getType())) {
                            IntentUtil.intentSlidIn(activity, CourseDetailActivity.class, 100, new BasicNameValuePair("cid", cfList.get(0).getKcid().toString()),
                                    new BasicNameValuePair("from", "all"));

                        } else {
                            if (!cfList.get(0).getUrl().toString().equals("")) {
                                IntentUtil.intentSlidIn(activity, CourseWebViewActivity.class, 200, new BasicNameValuePair("loadUrl", cfList.get(0).getUrl().toString()));
                            }
                        }
                    }else{
                        if("course".equals(cfList.get(position-1).getType())) {
                            IntentUtil.intentSlidIn(activity, CourseDetailActivity.class, 100, new BasicNameValuePair("cid", cfList.get(position-1).getKcid().toString()),
                                    new BasicNameValuePair("from", "all"));

                        }else{
                            if (!cfList.get(0).getUrl().toString().equals("")) {
                                IntentUtil.intentSlidIn(activity, CourseWebViewActivity.class, 200, new BasicNameValuePair("loadUrl", cfList.get(position - 1).getUrl().toString()));

                            }
                        }
                    }



                }
            });
            return imageViews.get(position);
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView(imageViews.get(position));
        }

    }

    class MyOnPageChangeListener implements OnPageChangeListener {

        @Override
        public void onPageScrollStateChanged(int arg0) {
            switch (arg0) {
                case 1:
                    isAutoPlay = false;
                    break;
                case 2:
                    isAutoPlay = true;
                    break;
                case 0:
                    if (vp.getCurrentItem() == 0) {
                        vp.setCurrentItem(count, false);
                    } else if (vp.getCurrentItem() == count + 1) {
                        vp.setCurrentItem(1, false);
                    }
                    currentItem = vp.getCurrentItem();
                    isAutoPlay = true;
                    break;
            }
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
        }

        @Override
        public void onPageSelected(int arg0) {
            for (int i = 0; i < iv_dots.size(); i++) {
                if (i == arg0 - 1) {
                    iv_dots.get(i).setImageResource(R.mipmap.dot_focus);
                } else {
                    iv_dots.get(i).setImageResource(R.mipmap.dot_blur);
                }
            }
        }

    }

}
